'use strict';
const { Forbbiden } = require('@utils/http-exception');

// 限制访问次数
module.exports = ({ maxCount, time }) => {
  return async (ctx, next) => {
    let count = 0;
    let startTime = new Date().getTime();
    if (new Date().getTime() - startTime >= time) {
      if (count >= maxCount) {
        count = 0;
        startTime = new Date().getTime();
        throw new Forbbiden('请求太频繁，请稍后再请求！');
      } else {
        count = 0;
        startTime = new Date().getTime();
        await next();
      }
    } else {
      count = count + 1;
      await next();
    }
  };
};
